angular.module('todoApp').directive('todoHeader', function() {
  return {
    templateUrl: './directives/todoHeader.html',
    scope: {
      onAdd: '&onAdd',
      onChangeOrder: '&onChangeOrder'
    },
    link: function(scope) {
      scope.content = '';
      scope.ascend = true;
      scope.addItem = function() {
        if (scope.form.$invalid) {
          return;
        }
        scope.onAdd({ content: scope.content });
        scope.clear();
      };
      scope.clear = function() {
        scope.content = '';
        scope.form.$setUntouched();
        scope.form.$setPristine();
      };
      scope.changeOrder = function() {
        scope.onChangeOrder({ascend: scope.ascend});
        scope.ascend = !scope.ascend;
      };
    }
  };
})
.directive('validateTodoContent', function() {
  const CONTENT_REGEXP = /^[a-z\d\s]+$/;
  return {
    require: 'ngModel',
    link: function(scope, elem, attrs, ctrl) {
      ctrl.$validators.todoContent = function(modelVal, viewVal) {
        if (ctrl.$isEmpty(viewVal)) {
          return true;
        }
        return CONTENT_REGEXP.test(viewVal);
      };
    }
  };
});